<template>
  <div class="follow-container">
    <!-- 顶部切换选项卡 -->
    <div class="tab-header">
      <button
          class="tab-btn"
          :class="{ active: currentType === 'follow' }"
          @click="switchType('follow')"
      >
        我的关注
      </button>
      <button
          class="tab-btn"
          :class="{ active: currentType === 'fans' }"
          @click="switchType('fans')"
      >
        我的粉丝
      </button>
    </div>

    <!-- 加载中提示 -->
    <div class="loading" v-if="loading">
      <el-icon class="is-loading"><Loading /></el-icon>
      加载中...
    </div>

    <!-- 列表内容区 -->
    <div class="list-container" v-else>
      <!-- 空数据提示 -->
      <div class="empty-tip" v-if="userList.length === 0">
        <el-empty
            :description="currentType === 'follow' ? '暂无关注数据~' : '暂无粉丝数据~'"
            :image-size="120"
        />
      </div>

      <!-- 用户列表 -->
      <div class="user-item" v-for="user in userList" :key="user.userId">
        <!-- 头像 -->
        <el-avatar
            class="user-avatar"
            :size="56"
            :src="getAvatarUrl(user.avatar)"
            alt="用户头像"
        />
        <!-- 信息区 -->
        <div class="user-info">
          <div class="nickname">{{ user.nickName }}</div>
          <div class="user-id">ID: {{ user.userId }}</div>
        </div>

        <!-- 操作按钮 -->
        <div class="user-actions">
          <!-- 发送消息按钮 -->
          <el-button
              class="msg-btn"
              @click="handleSendMessage(user)"
              :icon="ChatDotRound"
          >
            消息
          </el-button>

          <!-- 关注列表显示已关注按钮，可以取关 -->
          <el-button
              v-if="currentType === 'follow'"
              class="follow-btn followed"
              @click="handleUnfollow(user.userId)"
              :loading="user.unfollowing"
          >
            <el-icon><Check /></el-icon>
            已关注
          </el-button>

          <!-- 粉丝列表显示回关按钮 -->
          <el-button
              v-else-if="currentType === 'fans' && !user.isFollowed"
              class="follow-btn follow-back"
              @click="handleFollow(user.userId)"
              :loading="user.following"
          >
            <el-icon><Plus /></el-icon>
            关注
          </el-button>

          <!-- 粉丝列表显示互相关注 -->
          <el-button
              v-else-if="currentType === 'fans' && user.isFollowed"
              class="follow-btn mutual"
              disabled
          >
            <el-icon><UserFilled /></el-icon>
            互相关注
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Check, Plus, UserFilled, Loading, ChatDotRound } from '@element-plus/icons-vue'
import axios from '../api/index.js' // 引入已封装的axios

// 1. 响应式变量定义
const currentType = ref('follow') // 当前选中类型：默认关注列表
const userList = ref([]) // 存储用户列表数据
const loading = ref(false) // 加载状态
const router = useRouter()

// 2. 获取头像
const getAvatarUrl = (avatarName) => {
  if (!avatarName) {
    return 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png';
  }

  const baseURL = axios.defaults.baseURL || '';
  const cleanBaseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL;
  return `${cleanBaseURL}/img/avatar/${avatarName}`;
};

// 3. 数据请求函数：根据类型获取列表
const fetchFollowList = async () => {
  loading.value = true // 开始加载
  try {
    // 调用接口：传入当前类型（follow/fans）
    const response = await axios.get(`/follow/list/${currentType.value}`)
    userList.value = response || []

    // 为每个用户添加加载状态
    userList.value.forEach(user => {
      user.unfollowing = false
      user.following = false

      // 调试：打印用户数据，特别是 isFollowed 字段
      console.log(`用户 ${user.userId} - isFollowed:`, user.isFollowed, typeof user.isFollowed)
    })
  } catch (error) {
    console.error('获取列表失败：', error)
    userList.value = [] // 失败时清空列表
    ElMessage.error(currentType.value === 'follow' ? '获取关注列表失败' : '获取粉丝列表失败')
  } finally {
    loading.value = false // 结束加载
  }
}

// 4. 切换类型函数
const switchType = (type) => {
  if (currentType.value === type) return // 避免重复点击
  currentType.value = type // 更新当前类型
  fetchFollowList() // 重新请求对应类型数据
}

// 5. 取关处理
const handleUnfollow = async (userId) => {
  try {
    await ElMessageBox.confirm(
        '确定要取消关注吗？',
        '取消关注',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )

    // 设置当前用户的取消关注加载状态
    const user = userList.value.find(u => u.userId === userId)
    if (user) {
      user.unfollowing = true
    }

    // 调用取关接口
    await axios.put(`/follow/${userId}/false`)

    ElMessage.success('取消关注成功')

    // 重新获取列表
    await fetchFollowList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取关失败:', error)
      ElMessage.error('取关失败，请重试')
    }
  } finally {
    // 重置加载状态
    const user = userList.value.find(u => u.userId === userId)
    if (user) {
      user.unfollowing = false
    }
  }
}

// 6. 关注处理
const handleFollow = async (userId) => {
  try {
    const user = userList.value.find(u => u.userId === userId)
    if (user) {
      user.following = true
    }

    // 调用关注接口
    await axios.put(`/follow/${userId}/true`)

    ElMessage.success('关注成功')

    // 重新获取列表
    await fetchFollowList()
  } catch (error) {
    console.error('关注失败:', error)
    ElMessage.error('关注失败，请重试')
  } finally {
    const user = userList.value.find(u => u.userId === userId)
    if (user) {
      user.following = false
    }
  }
}

// 7. 发送消息处理
const handleSendMessage = (user) => {
  // 跳转到聊天界面，传递用户信息
  router.push({
    path: 'chat',
    query: {
      targetUserId: user.userId,
      targetUserName: user.nickName,
      targetUserAvatar: user.avatar
    }
  })
}

// 8. 组件挂载时默认请求关注列表
onMounted(() => {
  fetchFollowList()
})
</script>

<style scoped>
/* 容器整体样式 */
.follow-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 0 20px;
}

/* 选项卡样式 */
.tab-header {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
  border-bottom: 1px solid #e8e8e8;
  padding-bottom: 10px;
}

.tab-btn {
  padding: 12px 32px;
  border: none;
  border-radius: 8px;
  background-color: transparent;
  font-size: 16px;
  font-weight: 500;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.tab-btn.active {
  color: #1890ff;
  background-color: rgba(24, 144, 255, 0.1);
}

.tab-btn.active::after {
  content: '';
  position: absolute;
  bottom: -11px;
  left: 50%;
  transform: translateX(-50%);
  width: 80%;
  height: 3px;
  background-color: #1890ff;
  border-radius: 2px;
}

.tab-btn:hover:not(.active) {
  background-color: #f5f5f5;
  color: #333;
}

/* 加载中样式 */
.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 50px 0;
  color: #666;
  font-size: 16px;
}

/* 列表容器样式 */
.list-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 空数据提示 */
.empty-tip {
  text-align: center;
  padding: 40px 0;
}

/* 用户列表项样式 */
.user-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  border-radius: 12px;
  background-color: #fff;
  border: 1px solid #f0f0f0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.user-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
  border-color: #e0e0e0;
}

/* 头像样式 */
.user-avatar {
  flex-shrink: 0;
}

/* 用户信息样式 */
.user-info {
  flex: 1;
  min-width: 0;
}

.nickname {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.user-id {
  font-size: 14px;
  color: #999;
}

/* 操作按钮区域 */
.user-actions {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 消息按钮样式 */
.msg-btn {
  border-radius: 20px;
  padding: 8px 16px;
  font-size: 14px;
  font-weight: 500;
  color: #666;
  border-color: #e0e0e0;
  background-color: #fff;
  transition: all 0.3s ease;
}

.msg-btn:hover {
  color: #1890ff;
  border-color: #1890ff;
  background-color: rgba(24, 144, 255, 0.05);
}

.msg-btn:deep(.el-icon) {
  margin-right: 4px;
}

/* 关注按钮样式 */
.follow-btn {
  border-radius: 20px;
  padding: 8px 16px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.follow-btn:deep(.el-icon) {
  margin-right: 4px;
}

/* 已关注按钮 */
.follow-btn.followed {
  background-color: #f0f0f0;
  border-color: #f0f0f0;
  color: #666;
}

.follow-btn.followed:hover {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
  color: #fff;
}

/* 回关按钮 */
.follow-btn.follow-back {
  background-color: #1890ff;
  border-color: #1890ff;
  color: #fff;
}

.follow-btn.follow-back:hover {
  background-color: #40a9ff;
  border-color: #40a9ff;
}

/* 互相关注按钮 */
.follow-btn.mutual {
  background-color: #52c41a;
  border-color: #52c41a;
  color: #fff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .follow-container {
    padding: 0 16px;
  }

  .tab-header {
    gap: 12px;
  }

  .tab-btn {
    padding: 10px 20px;
    font-size: 14px;
  }

  .user-item {
    padding: 16px;
  }

  .user-info {
    min-width: 120px;
  }

  .nickname {
    font-size: 15px;
  }

  .user-id {
    font-size: 13px;
  }

  .user-actions {
    gap: 6px;
  }

  .msg-btn,
  .follow-btn {
    padding: 6px 12px;
    font-size: 13px;
  }

  /* 在移动端，消息按钮只显示图标 */
  .msg-btn span {
    display: none;
  }

  .msg-btn:deep(.el-icon) {
    margin-right: 0;
  }
}
</style>